<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="btnController">
        <el-button class="buttons" @click="handleCreate">
          添加
        </el-button>
      </div>
      <div class="formContainer">
        <label class="filterLabel">关键词:</label>
        <el-input v-model="listQuery.keyword" placeholder="请输入用户名/姓名" class="filterInput" @keyup.enter.native="handleFilter" />
        <label class="filterLabel">状态:</label>
        <el-select v-model="listQuery.status" class="search-select" clearable placeholder="请选择">
          <el-option label="所有" :value="0" />
          <el-option label="正常" :value="1" />
          <el-option label="冻结" :value="2" />
        </el-select>
        <el-button class="buttons" @click="handleFilter">
          搜索
        </el-button>
      </div>
    </div>
    <el-table
      :key="tableKey"
      :data="list"
      style="width: 100%;"
      :header-cell-style="{background:'#ebebeb',height:'#54px'}"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="真实姓名" align="center">
        <template slot-scope="{row}">
          <span>{{ row.realname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属组别" align="center">
        <template slot-scope="{row}">
          <span>{{ row.groups_text }}</span>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" min-width="150px">
        <template slot-scope="{row}">
          {{ row.email }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.status_text }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template v-if="row.id!=1" slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-popconfirm
            confirm-button-text="好的"
            cancel-button-text="不用了"
            icon="el-icon-info"
            icon-color="red"
            title="删除后不可以恢复，确定删除吗？"
            @onConfirm="handleDelete(row,$index)"
          >
            <el-button slot="reference" size="mini" type="danger">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.per_page" @pagination="getList" />
    <!-- 编辑、 添加弹框表单 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="rows" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="角色组" prop="groupid">
          <el-select v-model="rows.groupid" multiple class="filter-item" placeholder="请选择">
            <el-option v-for="(item,index) in groupOptions" :key="index" :label="item.name" :value="parseInt(item.id)" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="rows.username" placeholder="请输入用户名 字母加数字" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="rows.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="rows.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname">
          <el-input v-model="rows.realname" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item v-if="false" label="昵称">
          <el-input v-model="rows.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="rows.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="头像">
          <Upload v-model="rows.face" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
    <!--  -->
    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, add, edit, del, rows } from '@/api/manager'
import { fetchList as roleGroup } from '@/api/managerRole'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import Upload from '@/components/Upload/uploadImg'
import { notifySuccess } from '@/utils/message'
export default {
  name: 'AttachmentIndex',
  components: { Pagination, Upload },
  filters: {
    statusFilter(status) {
      const statusMap = {
        normal: '正常',
        hidden: '隐藏'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      groupOptions: {},
      iconsShow: false,
      tableKey: 0,
      list: null,
      total: 0,
      listQuery: {
        page: 1,
        per_page: 15,
        status: null,
        importance: undefined,
        keyword: '',
        type: undefined,
        sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: { 'normal': '正常', 'hidden': '隐藏' },
      showReviewer: false,
      rows: {
        groupid: null,
        username: '',
        password: '',
        mobile: '',
        realname: '',
        nickname: 1,
        status: 'normal',
        email: '',
        face: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '更新',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        groupid: [{ required: true, message: '角色组不能为空', trigger: 'change' }],
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        // password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
        realname: [{ required: true, message: '真实姓名', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    getList() {
      var that = this
      const kw = this.listQuery.keyword
      this.listQuery.keyword = kw.trim()
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        console.log(response)
        this.list = response.data.data
        this.total = response.data.total
        // Just to simulate the time of the request
        setTimeout(() => {
          console.log(213)
          that.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetRows() {
      this.rows = {
        groupid: null,
        username: '',
        password: '',
        mobile: '',
        realname: '',
        nickname: 1,
        status: 'normal',
        email: '',
        face: ''
      }
    },
    handleCreate() {
      this.getGroups()
      this.resetRows()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 新增提交方法
    createData() {
      const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.rows)
          add(tempData).then(res => {
            that.list.unshift(this.temp)
            that.dialogFormVisible = false
            that.getList()
            notifySuccess(res.msg || '添加成功')
          })
        }
      })
    },
    // 编辑数据
    handleUpdate(row) {
      const that = this
      this.getGroups()
      rows(row.uuid).then(function(res) {
        that.rows = Object.assign({}, res.data) // copy obj
        that.rows.uuid = row.uuid
      })
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.rows)
          edit(tempData.uuid, tempData.groupid,
            tempData.username,
            tempData.password,
            tempData.mobile,
            tempData.realname,
            tempData.nickname,
            tempData.status,
            tempData.email,
            tempData.face).then((res) => {
            const index = that.list.findIndex(v => v.id === that.rows.ids)
            that.list.splice(index, 1, that.rows)
            that.dialogFormVisible = false
            notifySuccess(res.msg || '编辑成功')
          })
        }
      })
    },
    // 删除操作
    handleDelete(row, index) {
      del(row.uuid).then(res => {
        notifySuccess('删除成功')
        this.list.splice(index, 1)
      })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    getGroups() {
      roleGroup().then(res => {
        this.groupOptions = res.data.data
      })
    }
  }
}
</script>
